package com.gupao.practice.data20200223;

import com.gupao.practice.data20200223.exception.NotSupportedPaymentType;

import java.io.FileInputStream;
import java.net.URL;
import java.util.*;

/**
 * 国内支付
 *
 * @author ZhenZhong
 * @date 2020/2/24
 */
public abstract class AbstractPaymentFactory implements PaymentFactory {

    private final List<PaymentSupport> payments = new ArrayList<PaymentSupport>();

    public AbstractPaymentFactory() {
        try {
            Enumeration<URL> resources = this.getClass().getClassLoader().getResources(getConfigFile());
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                Properties properties = new Properties();
                properties.load(new FileInputStream(url.getFile()));
                for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                    String className = (String) entry.getValue();
                    payments.add(new PaymentSupport(className, (Payment) Class.forName(className).newInstance()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Payment create(Class<? extends Payment> clazz) {
        for (PaymentSupport support : getPayments()) {
            if (support.getPayType().equalsIgnoreCase(clazz.getName())) {
                return support.getPayment();
            }
        }
        throw new NotSupportedPaymentType();
    }

    public List<PaymentSupport> getPayments() {
        return payments;
    }

    /**
     * 获取配置文件
     *
     * @return
     */
    protected abstract String getConfigFile();

}
